package com.tongle.frs.common.util.security;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;

public class TripleDES
{
  private static final String KEY_ALGORITHM = "DESede";
  private static final String CIPHER_ALGORITHM_ECB = "DESede/ECB/PKCS5Padding";
  private static final String CIPHER_ALGORITHM_CBC = "DESede/CBC/PKCS5Padding";
  private static final String ENCODING = "UTF-8";
  private String keySeed = "0123456789zxcv0123456789";
  private SecretKey secretKey;
  private Cipher cipher;

  public TripleDES()
    throws Exception
  {
    this("ECB");
  }

  public TripleDES(String mode)
    throws Exception
  {
    this.secretKey = new SecretKeySpec(this.keySeed.getBytes("UTF-8"), "DESede");

    if ("ECB".equals(mode))
      this.cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
    else if ("CBC".equals(mode))
      this.cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
  }

  public synchronized byte[] encrypt(String str)
    throws Exception
  {
    this.cipher.init(1, this.secretKey);
    return this.cipher.doFinal(str.getBytes());
  }

  public synchronized byte[] decrypt(byte[] encrypt)
    throws Exception
  {
    this.cipher.init(2, this.secretKey);
    return this.cipher.doFinal(encrypt);
  }

  private byte[] getIV(String iv)
    throws UnsupportedEncodingException
  {
    String thisIV = iv;
    if (thisIV == null) {
      thisIV = "12345678";
    }
    return thisIV.getBytes("UTF-8");
  }

  public synchronized byte[] encrypt_cbc(String str)
    throws Exception
  {
    this.cipher.init(1, this.secretKey, 
      new IvParameterSpec(getIV("12345678")));

    return this.cipher.doFinal(str.getBytes("utf-8"));
  }

  public synchronized byte[] decrypt_cbc(byte[] encrypt)
    throws Exception
  {
    this.cipher.init(2, this.secretKey, 
      new IvParameterSpec(getIV("12345678")));

    return this.cipher.doFinal(encrypt);
  }

  public String getKeySeed() {
    return this.keySeed;
  }

  public void setKeySeed(String keySeed) throws Exception {
    this.keySeed = keySeed;
    this.secretKey = new SecretKeySpec(keySeed.getBytes("UTF-8"), "DESede");
  }
}